package com.ecar.api.service.manager.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ecar.api.service.manager.StaffService;
import com.ecar.api.support.util.DateUtil;
import com.ecar.api.support.util.PasswordUtil;
import com.ecar.api.support.util.Redis;
import com.ecar.api.support.util.UuidUtils;
import com.ecar.common.dto.DataBean;
import com.ecar.common.util.StringUtil;
import com.ecar.core.common.entity.EcarUser;
import com.ecar.core.manager.dao.LogLoginMapper;
import com.ecar.core.manager.dao.StaffMapper;
import com.ecar.core.manager.entity.LogLogin;
import com.ecar.core.manager.entity.Staff;
import com.ecar.core.common.dao.EcarUserMapper;
import com.ecar.core.common.dao.RoleAuthorityMapper;
import com.ecar.core.common.dao.UserRoleMapper;

@Service
@Transactional
public class StaffServiceImpl implements StaffService {
	
	@Autowired
	LogLoginMapper logLoginMapper;
	
	@Autowired
	StaffMapper staffMapper;
	
	@Autowired
	EcarUserMapper ecarUserMapper;
	
	@Autowired
	UserRoleMapper userRoleMapper;
	
	@Autowired
	RoleAuthorityMapper roleAuthorityMapper;
	
	@Override
	public DataBean login(JSONObject fields, String ip) {
		String username = fields.getString("username");
		String password = fields.getString("password");
		String browser = fields.containsKey("browser") ? fields.getString("browser") : null;
		if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
			return new DataBean(400, "用户名和密码不能为空！");
		}
		
		Staff staff = staffMapper.queryByUsername(username);
		EcarUser ecarUser=ecarUserMapper.findByUsername(username);
		if (staff == null) return new DataBean(404, "登录失败，用户未找到。");
		if (ecarUser.getType() != EcarUser.TYPE_STAFF) return new DataBean(403, "登录失败，无效的用户账号！");
		if (ecarUser.getStatus() == EcarUser.STATUS_INVALID)
			return new DataBean(403, "登录失败，账号未激活！");
		
		
		String key = Redis.K.MANAGER_LOGIN.to(DateUtil.getCurDateYYYYMMDD(), ip+username);
		int count;
		if(Redis.c.exists(key)){
			count = Integer.valueOf(Redis.c.get(key));
		}else{
			count=0;
		}
		
		if(count>=5){
			return new DataBean(403,"登陆失败超过次数，限制登陆,请联系客服",null);
		}
		
		if (!password.equals(PasswordUtil.desdecode(ecarUser.getPassword()))){
			Redis.c.del(key);
			Redis.c.setex(Redis.K.MANAGER_LOGIN.to(DateUtil.getCurDateYYYYMMDD(),ip+username), Redis.DAY, (count+1)+"");
			return new DataBean(403, "登录失败，密码错误。");
		}
		
		Redis.c.del(key);

		// 获取工作人员角色和权限
		List<Integer> roleIds = userRoleMapper.getRoleIdsByUserId(ecarUser.getId());
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("roleIds", roleIds);
		if (roleIds != null && roleIds.size() > 0) {
			ecarUser.setRoles(userRoleMapper.getRoleCodesByUserId(ecarUser.getId()));
			ecarUser.setAuths(roleAuthorityMapper.getAuthCodesByRoleIds(map));
		}

		ecarUser.setLastLoginTime(new Date());
		ecarUserMapper.updateByPrimaryKeySelective(ecarUser);

		//登录日志
		LogLogin logLogin = new LogLogin();
		logLogin.setId(UuidUtils.getUUID());
		logLogin.setUsername(username);
		logLogin.setUserId(ecarUser.getId());
		logLogin.setIp(ip);
		logLogin.setLoginTime(new Date());
		logLogin.setLoginDevice("PC");
		logLogin.setDeviceInfo(browser);
		logLoginMapper.insert(logLogin);

		return new DataBean(200,ecarUser);
	}

	@Override
	public DataBean setPasswordByPhone(String pwd, String phone, String captcha) {
		String key = Redis.K.CAPTCHA.to(phone);
		String code = Redis.c.get(key);
		if (!captcha.equals(code)) return new DataBean(403, new JSONObject() ,"验证码错误！");

		Staff staff = staffMapper.findByPhone(phone);
		if(staff==null){
			return new DataBean(403,new JSONObject(),"手机号错误");
		}
		staff.setPassword(PasswordUtil.desencode(pwd));
		staff.setLastLoginTime(new Date());
		staffMapper.updateByPrimaryKeySelective(staff);
		Redis.c.del(key);

		return new DataBean();
	}
}
